package com.core.db.require;

import java.sql.SQLException;
import java.util.List;

import com.core.db.condition.Condition;

class Update extends BaseRequire
{
	private String table;
	private Condition cond;
	private List< ColumnDescribe > describes;

	public Update( String table, List< ColumnDescribe > describes, Condition cond )
	{
		this.table = table;
		this.describes = describes;
		this.cond = cond;
	}

	@Override
	public String sql() throws SQLException
	{
		if ( cond == null || table == null || table.length() == 0 )
		{
			throw new SQLException( "No table to be found to be operated on" );
		}
		List< String > columns = getColumns();
		List< Object > values = getValues();
		if ( columns == null || columns.size() == 0 || values == null || values.size() == 0
						|| columns.size() != values.size() )
		{
			throw new SQLException( "Disagreement between columns and values" );
		}
		StringBuffer buffer = new StringBuffer();
		buffer.append( "UPDATE" ).append( " " ).append( table );
		buffer.append( " SET " );
		buffer.append( assembleColumns( getColumns() ) ).append( " " );
		buffer.append( assembleWhere( cond ) );
		return buffer.toString();
	}

	@Override
	protected String assembleColumns( List< String > columns )
	{
		StringBuffer buffer = new StringBuffer();
		int maxIndex = columns.size() - 1;
		for ( int i = 0; i < maxIndex; i++ )
		{
			buffer.append( columns.get( i ) ).append( "=" ).append( "?" ).append( "," );
		}
		buffer.append( columns.get( maxIndex ) ).append( "=" ).append( "?" );
		return buffer.toString();
	}

	@Override
	public List< ColumnDescribe > getColumnDescribes()
	{
		return describes;
	}

	@Override
	public Condition getCondition()
	{
		return cond;
	}
}
